package com.raos.example.mongo;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Arrays;

/**
 * mongodb java客户端访问
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/8/29 21:25
 */
public class MongoClientTest {

    public static void main(String[] args) {
        // 连接到 mongodb 服务
        MongoClient mongoClient = MongoClients.create("mongodb://127.0.0.1:27017");
        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("mycoll");
        System.out.println("Connect to database successfully");

        // 获取到集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("mytest");

        // 创建文档
        Document doc = new Document("name", "MongoDB")
                .append("type", "database")
                .append("count", 1)
                .append("versions", Arrays.asList("v3.12.5", "v3.12.6", "v3.12.7"));

        // 插入数据
        collection.insertOne(doc);
        System.out.println("插入完成");
    }

}
